<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
</head>

<body>
    <video controls></video>
    <script>
        var video = document.querySelector('video');


        //   var assetURL = '../assets/video/fmp4_h265_1080_608.mp4';//video/mp4; codecs="avc1.64001f,mp4a.40.2"
        var assetURL = '../assets/video/frag_bunny.mp4';//video/mp4; codecs="avc1.42E01E, mp4a.40.2"

        // Need to be specific for Blink regarding codecs
        // ./mp4info frag_bunny.mp4 | grep Codec
        var mimeCodec = 'video/mp4; codecs="avc1.64001f, mp4a.40.2"';//
        //  var mimeCodec = 'video/mp4;codecs="avc1.42E01E,mp4a.40.2"';//

        if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) {
            var mediaSource = new MediaSource;
            //console.log(mediaSource.readyState); // closed
            video.src = URL.createObjectURL(mediaSource);
            mediaSource.addEventListener('sourceopen', sourceOpen);
        } else {
            console.error('Unsupported MIME type or codec: ', mimeCodec);
        }

        function sourceOpen(_) {
            //console.log(this.readyState); // open
            var mediaSource = this;
            var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
            //这里演示的一次性加载所有数据然后塞给sourceBuffer
            fetchAB(assetURL, function (buf) {
                sourceBuffer.addEventListener('updateend', function (_) {
                    console.log("updateend");
                    mediaSource.endOfStream();
                    //塞完数据后开始播放
                    video.play();
                    //console.log(mediaSource.readyState); // ended
                });
                console.log("len " + buf.byteLength);
                sourceBuffer.appendBuffer(buf);
                //  sourceBuffer.appendBuffer(new Uint8Array(1));
            });
        };

        function fetchAB(url, cb) {
            console.log(url);
            var xhr = new XMLHttpRequest;
            xhr.open('get', url);
            xhr.responseType = 'arraybuffer';
            xhr.onload = function () {
                cb(xhr.response);
            };
            xhr.send();
        };
    </script>
</body>

</html>